package org.Lin.server;

import org.Lin.util.AESUtil;
import org.Lin.util.DatabaseUtil;
import org.Lin.util.LogUtil;
import org.json.JSONObject;
import java.sql.*;

public class RegisterServer {

    public static void handle(JSONObject json) {
        String userID = json.getString("userID");
        String name = json.getString("name");
        String passwordHash = json.getString("password");
        String email = json.getString("email");

        try (Connection conn = DatabaseUtil.getConnection()) {
            String checkSql = "SELECT * FROM User WHERE userID = ?";
            PreparedStatement checkStmt = conn.prepareStatement(checkSql);
            checkStmt.setString(1, userID);
            ResultSet rs = checkStmt.executeQuery();

            if (rs.next()) {
                JSONObject error = new JSONObject();
                error.put("type", "register_failed");
                error.put("message", "该用户ID已存在");
                NetworkServer.send(AESUtil.encrypt(error.toString()));
                return;
            }

            String insertSql = "INSERT INTO User(userID, name, password, email) VALUES (?, ?, ?, ?)";
            PreparedStatement stmt = conn.prepareStatement(insertSql);
            stmt.setString(1, userID);
            stmt.setString(2, name);
            stmt.setString(3, passwordHash);
            stmt.setString(4, email);
            stmt.executeUpdate();

            JSONObject success = new JSONObject();
            success.put("type", "register_success");
            success.put("message", "注册成功，请登录");
            NetworkServer.send(AESUtil.encrypt(success.toString()));

            LogUtil.logOperation("User", "register", "新用户注册: " + userID);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
